<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 7.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/favicon.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/favicon.ico">
  <link rel="mask-icon" href="/favicon.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="/lib/@fortawesome/fontawesome-free/css/all.min.css" integrity="sha256-5eIC48iZUHmSlSUz9XtjRyK2mzQkHScZY1WdMaoz74E=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/animate.css/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"blog.dqv5.com","root":"/","images":"/images","scheme":"Mist","darkmode":true,"version":"8.21.1","exturl":false,"sidebar":{"position":"right","width_expanded":320,"width_dual_column":240,"display":"always","padding":18,"offset":12},"hljswrap":true,"copycode":{"enable":true,"style":null},"fold":{"enable":true,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"gitalk","storage":true,"lazyload":false,"nav":null,"activeClass":"gitalk"},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"top_n_per_article":1,"unescape":false,"preload":false,"trigger":"auto"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="前段时间买了个树莓派，打电信客服开通了外网ip，相当于在家里搭了一个云服务器。今天有时间记录一下当时的搭建过程。">
<meta property="og:type" content="article">
<meta property="og:title" content="Python实现阿里云动态域名解析">
<meta property="og:url" content="http://blog.dqv5.com/2021/06/04/aliyun-ddns/index.html">
<meta property="og:site_name" content="dqv5.com">
<meta property="og:description" content="前段时间买了个树莓派，打电信客服开通了外网ip，相当于在家里搭了一个云服务器。今天有时间记录一下当时的搭建过程。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://image.dqv5.com/public/2021/06/04/1622815809532.png">
<meta property="og:image" content="https://image.dqv5.com/public/2021/06/04/1622816127650.png">
<meta property="og:image" content="https://image.dqv5.com/public/2021/06/04/1622815307449.png">
<meta property="og:image" content="https://image.dqv5.com/public/2021/06/04/1622815394458.png">
<meta property="og:image" content="https://image.dqv5.com/public/2021/06/04/1622816738485.png">
<meta property="og:image" content="https://image.dqv5.com/public/2021/06/04/1622818069648.png">
<meta property="article:published_time" content="2021-06-04T21:46:17.000Z">
<meta property="article:modified_time" content="2024-11-23T11:58:37.867Z">
<meta property="article:author" content="du qian">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://image.dqv5.com/public/2021/06/04/1622815809532.png">


<link rel="canonical" href="http://blog.dqv5.com/2021/06/04/aliyun-ddns/">


<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://blog.dqv5.com/2021/06/04/aliyun-ddns/","path":"2021/06/04/aliyun-ddns/","title":"Python实现阿里云动态域名解析"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Python实现阿里云动态域名解析 | dqv5.com</title>
  

  <script src="/js/third-party/analytics/baidu-analytics.js"></script>
  <script async src="https://hm.baidu.com/hm.js?1752ae624eedea5ce859335ad2f0e657"></script>







  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">dqv5.com</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">49</span></a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">20</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">61</span></a></li><li class="menu-item menu-item-留言板"><a href="/message-board/" rel="section"><i class="fa fa-comments fa-fw"></i>留言板</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
      <div class="search-header">
        <span class="search-icon">
          <i class="fa fa-search"></i>
        </span>
        <div class="search-input-container">
          <input autocomplete="off" autocapitalize="off" maxlength="80"
                placeholder="搜索..." spellcheck="false"
                type="search" class="search-input">
        </div>
        <span class="popup-btn-close" role="button">
          <i class="fa fa-times-circle"></i>
        </span>
      </div>
      <div class="search-result-container">
        <div class="search-result-icon">
          <i class="fa fa-spinner fa-pulse fa-5x"></i>
        </div>
      </div>
    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%BC%80%E9%80%9A%E5%A4%96%E7%BD%91IP%E5%9C%B0%E5%9D%80"><span class="nav-text">开通外网IP地址</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%A4%A9%E7%BF%BC%E7%BD%91%E5%85%B3%E7%AB%AF%E5%8F%A3%E6%98%A0%E5%B0%84"><span class="nav-text">天翼网关端口映射</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%B7%AF%E7%94%B1%E5%99%A8%E8%AE%BE%E7%BD%AEIP%E4%B8%8EMAC%E7%BB%91%E5%AE%9A"><span class="nav-text">路由器设置IP与MAC绑定</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%B7%AF%E7%94%B1%E5%99%A8%E7%AB%AF%E5%8F%A3%E8%BD%AC%E5%8F%91"><span class="nav-text">路由器端口转发</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9C%80%E7%BB%88%E8%BD%AC%E5%8F%91%E6%95%88%E6%9E%9C"><span class="nav-text">最终转发效果</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8A%A8%E6%80%81%E5%9F%9F%E5%90%8D%E8%A7%A3%E6%9E%90%EF%BC%88DDNS%EF%BC%89"><span class="nav-text">动态域名解析（DDNS）</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="du qian"
      src="/images/soccer.jpg">
  <p class="site-author-name" itemprop="name">du qian</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">61</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">20</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">49</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/duqian42707" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;duqian42707" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://stackoverflow.com/duqian42707" title="StackOverflow → https:&#x2F;&#x2F;stackoverflow.com&#x2F;duqian42707" rel="noopener me" target="_blank"><i class="fab fa-stack-overflow fa-fw"></i>StackOverflow</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://blog.csdn.net/duqian42707" title="CSDN → https:&#x2F;&#x2F;blog.csdn.net&#x2F;duqian42707" rel="noopener me" target="_blank"><i class="fas fa-link fa-fw"></i>CSDN</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://duqian42707.github.io/qiniu-host" title="图床 → https:&#x2F;&#x2F;duqian42707.github.io&#x2F;qiniu-host" rel="noopener me" target="_blank"><i class="far fa-image fa-fw"></i>图床</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://blog.dqv5.com/2021/06/04/aliyun-ddns/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/soccer.jpg">
      <meta itemprop="name" content="du qian">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="dqv5.com">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Python实现阿里云动态域名解析 | dqv5.com">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Python实现阿里云动态域名解析
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-06-04 21:46:17" itemprop="dateCreated datePublished" datetime="2021-06-04T21:46:17+00:00">2021-06-04</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2024-11-23 11:58:37" itemprop="dateModified" datetime="2024-11-23T11:58:37+00:00">2024-11-23</time>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>摘要：前段时间买了个树莓派，打电信客服开通了外网ip，相当于在家里搭了一个云服务器。今天有时间记录一下当时的搭建过程。</p>
<!-- more -->

<h2 id="开通外网IP地址"><a href="#开通外网IP地址" class="headerlink" title="开通外网IP地址"></a>开通外网IP地址</h2><p>我家用的电信宽带，拨打电话10000，找人工客服，就说开通外网IP业务，等待办理成功即可。</p>
<p>办理成功后，便可通过外网IP访问到你的天翼网关。（注意：80、443端口会被屏蔽，其它端口可以正常使用。）</p>
<p>再到阿里云配置一下域名解析，即可通过域名访问。操作方法见<a target="_blank" rel="noopener" href="https://help.aliyun.com/document_detail/29727.html">文档</a>。</p>
<h2 id="天翼网关端口映射"><a href="#天翼网关端口映射" class="headerlink" title="天翼网关端口映射"></a>天翼网关端口映射</h2><p><img src="https://image.dqv5.com/public/2021/06/04/1622815809532.png"></p>
<p>输入超级管理员的账号密码，注意不是普通用户的账户密码。</p>
<p>如果没改过的话，账号：<code>telecomadmin</code>   密码：<code>nE7jA%5m</code></p>
<p>如果密码不对，那就只能问电信工作人员了。</p>
<p>登录成功之后，进入【应用】-【高级NAT配置】-【虚拟服务器设置】，添加端口映射规则。即将你外网ip的端口映射到内网ip的端口。</p>
<p>这里两种情况:</p>
<ol>
<li><p>如果家里装了路由器，所有设备（手机、电脑、树莓派）都是连的路由器，这里就映射到路由器的IP，然后再在路由器设置一次端口映射。</p>
</li>
<li><p>如果家里没装路由器，设备直接连接的天翼网关，那么这里就直接映射设备的ip。注意这里要给设备设置为固定ip地址。</p>
</li>
</ol>
<p><img src="https://image.dqv5.com/public/2021/06/04/1622816127650.png"></p>
<h2 id="路由器设置IP与MAC绑定"><a href="#路由器设置IP与MAC绑定" class="headerlink" title="路由器设置IP与MAC绑定"></a>路由器设置IP与MAC绑定</h2><p><img src="https://image.dqv5.com/public/2021/06/04/1622815307449.png"></p>
<p><img src="https://image.dqv5.com/public/2021/06/04/1622815394458.png"></p>
<h2 id="路由器端口转发"><a href="#路由器端口转发" class="headerlink" title="路由器端口转发"></a>路由器端口转发</h2><p><img src="https://image.dqv5.com/public/2021/06/04/1622816738485.png"></p>
<h2 id="最终转发效果"><a href="#最终转发效果" class="headerlink" title="最终转发效果"></a>最终转发效果</h2><pre class="mermaid">graph LR
用户 --> http://domain.com:10000 --> 天翼网关10000端口 --> TPLink路由器10000端口 --> 树莓派80端口</pre>



<h2 id="动态域名解析（DDNS）"><a href="#动态域名解析（DDNS）" class="headerlink" title="动态域名解析（DDNS）"></a>动态域名解析（DDNS）</h2><p>这一套搞好之后，刚开始用着还比较舒服，用了一段时间后，问题暴露出来了。电信的外网IP是不固定的，隔一段时间就会变。虽然我可以上阿里云控制台，去修改域名对应的ip地址，但是手动去改是很烦的。能不能实现自动修改呢？答案是肯定的。</p>
<p>阿里云提供了修改域名解析的<a target="_blank" rel="noopener" href="https://next.api.aliyun.com/document/Alidns/2015-01-09/UpdateDomainRecord">API</a>和<a target="_blank" rel="noopener" href="https://next.api.aliyun.com/api/Alidns/2015-01-09/UpdateDomainRecord?params=%7B%7D">SDK</a>。我们可以根据这些自己写程序来实现动态域名解析。</p>
<p>思路大概就是，定时(每隔15分钟)查询一下当前的外网IP，看是否发生了变化，如果变化了，则调用阿里云API修改域名解析。</p>
<p>废话少说，python代码如下，只需加入系统定时任务即可。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">root@raspberrypi:~ <span class="comment"># crontab -e</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 每隔15分钟检查一次公网ip是否发生变化</span></span><br><span class="line">0,15,30,45 * * * *  /opt/alidns/main.py</span><br></pre></td></tr></table></figure>



<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#!/usr/bin/env python</span></span><br><span class="line"><span class="comment">#-*- coding: utf-8 -*-</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"><span class="keyword">import</span> json</span><br><span class="line"><span class="keyword">import</span> logging</span><br><span class="line"><span class="keyword">from</span> urllib2 <span class="keyword">import</span> urlopen</span><br><span class="line"><span class="keyword">from</span> aliyunsdkcore.client <span class="keyword">import</span> AcsClient</span><br><span class="line"><span class="keyword">from</span> aliyunsdkcore.acs_exception.exceptions <span class="keyword">import</span> ClientException</span><br><span class="line"><span class="keyword">from</span> aliyunsdkcore.acs_exception.exceptions <span class="keyword">import</span> ServerException</span><br><span class="line"><span class="keyword">from</span> aliyunsdkalidns.request.v20150109 <span class="keyword">import</span> DescribeDomainRecordsRequest</span><br><span class="line"><span class="keyword">from</span> aliyunsdkalidns.request.v20150109 <span class="keyword">import</span> UpdateDomainRecordRequest</span><br><span class="line"><span class="keyword">import</span> sys</span><br><span class="line"></span><br><span class="line">reload(sys)</span><br><span class="line">sys.setdefaultencoding(<span class="string">&#x27;utf8&#x27;</span>)</span><br><span class="line"></span><br><span class="line">logging.basicConfig(level=logging.INFO,<span class="built_in">format</span> = <span class="string">&#x27;%(asctime)s - %(name)s - %(levelname)s - %(message)s&#x27;</span>,filename=<span class="string">&#x27;/opt/alidns/log/alidns.log&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">DnsHandler</span>:</span><br><span class="line">    <span class="comment"># 从阿里云开发者后台获取Access_Key_Id和Access_Key_Secret</span></span><br><span class="line">    access_key_id = <span class="string">&quot; &quot;</span></span><br><span class="line">    access_key_secret = <span class="string">&quot; &quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 填入自己的域名</span></span><br><span class="line">    domain_name = <span class="string">&quot;domain.com&quot;</span></span><br><span class="line">    <span class="comment"># 填入二级域名的RR值</span></span><br><span class="line">    rr_keyword = <span class="string">&quot;test&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 解析记录类型，一般为A记录</span></span><br><span class="line">    record_type = <span class="string">&quot;A&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 用于储存解析记录的文件名</span></span><br><span class="line">    file_name = <span class="string">&quot;/opt/alidns/ip_addr.txt&quot;</span></span><br><span class="line"></span><br><span class="line">    client = <span class="literal">None</span></span><br><span class="line">    record = <span class="literal">None</span></span><br><span class="line">    current_ip  = <span class="string">&#x27;&#x27;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 初始化，获取client实例</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self</span>):</span><br><span class="line">        self.client = AcsClient(</span><br><span class="line">            self.access_key_id,</span><br><span class="line">            self.access_key_secret</span><br><span class="line">        )</span><br><span class="line">        self.record = self.get_record()</span><br><span class="line">        self.current_ip = self.get_current_ip()</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 如果公网IP发生变化，则自动修改阿里云解析记录</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">reset</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">if</span> self.current_ip &lt;&gt; self.get_record_value():</span><br><span class="line">            self.update_record(self.current_ip)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">			logging.info(<span class="string">&#x27;ip 地址未发生变化:&#x27;</span> + self.current_ip)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 获取阿里云域名解析完整记录，并使用文件缓存</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">get_record</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">if</span> os.path.isfile(self.file_name) :</span><br><span class="line">            file_handler = <span class="built_in">open</span>(self.file_name, <span class="string">&#x27;r&#x27;</span>)</span><br><span class="line">            r = file_handler.read()</span><br><span class="line">            file_handler.close()</span><br><span class="line">        <span class="keyword">else</span> :</span><br><span class="line">            request = DescribeDomainRecordsRequest.DescribeDomainRecordsRequest()</span><br><span class="line">            request.set_PageSize(<span class="number">10</span>)</span><br><span class="line">            request.set_action_name(<span class="string">&quot;DescribeDomainRecords&quot;</span>)</span><br><span class="line">            request.set_DomainName(self.domain_name)</span><br><span class="line">            request.set_RRKeyWord(self.rr_keyword)</span><br><span class="line">            request.set_TypeKeyWord(self.record_type)</span><br><span class="line">            r = self.client.do_action_with_exception(request)</span><br><span class="line">            file_handler = <span class="built_in">open</span>(self.file_name, <span class="string">&#x27;w&#x27;</span>)</span><br><span class="line">            file_handler.write(r)</span><br><span class="line">            file_handler.close()</span><br><span class="line">        <span class="keyword">return</span> json.loads(r)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 获取阿里云域名解析记录ID</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">get_record_id</span>(<span class="params">self</span>) :</span><br><span class="line">        <span class="keyword">return</span> self.record[<span class="string">&quot;DomainRecords&quot;</span>][<span class="string">&quot;Record&quot;</span>][<span class="number">0</span>][<span class="string">&quot;RecordId&quot;</span>]</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 获取当前域名解析记录</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">get_record_value</span>(<span class="params">self</span>) :</span><br><span class="line">        <span class="keyword">return</span> self.record[<span class="string">&quot;DomainRecords&quot;</span>][<span class="string">&quot;Record&quot;</span>][<span class="number">0</span>][<span class="string">&quot;Value&quot;</span>]</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 修改阿里云解析记录</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">update_record</span>(<span class="params">self, value</span>):</span><br><span class="line">        request = UpdateDomainRecordRequest.UpdateDomainRecordRequest()</span><br><span class="line">        request.set_action_name(<span class="string">&quot;UpdateDomainRecord&quot;</span>)</span><br><span class="line">        request.set_RecordId(self.get_record_id())</span><br><span class="line">        request.set_Type(self.record_type)</span><br><span class="line">        request.set_RR(self.rr_keyword)</span><br><span class="line">        request.set_Value(value)</span><br><span class="line">        self.client.do_action_with_exception(request)</span><br><span class="line">        os.remove(self.file_name)</span><br><span class="line">        logging.info(<span class="string">&#x27;ip地址变化，更新DNS解析：&#x27;</span> + value);</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 获取当前公网IP</span></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">get_current_ip</span>(<span class="params">self</span>):</span><br><span class="line">        currentip = json.load(urlopen(<span class="string">&#x27;https://ipv4.jsonip.com&#x27;</span>))[<span class="string">&#x27;ip&#x27;</span>]</span><br><span class="line">        logging.debug(<span class="string">&#x27;currentip:&#x27;</span> + currentip)</span><br><span class="line">        <span class="keyword">return</span> currentip</span><br><span class="line"></span><br><span class="line"><span class="comment"># 实例化类并启动更新程序</span></span><br><span class="line">dns = DnsHandler()</span><br><span class="line">dns.reset()</span><br></pre></td></tr></table></figure>

<p><img src="https://image.dqv5.com/public/2021/06/04/1622818069648.png"></p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="reward-container">
  <div>请我一杯咖啡吧！</div>
  <button>
    赞赏
  </button>
  <div class="post-reward">
      <div>
        <img src="/images/wechatpay.jpg" alt="du qian 微信">
        <span>微信</span>
      </div>
      <div>
        <img src="/images/alipay.jpg" alt="du qian 支付宝">
        <span>支付宝</span>
      </div>

  </div>
</div>


        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/04/04/tampermonkey-request-intercept/" rel="prev" title="通过油猴插件拦截并修改ajax请求">
                  <i class="fa fa-angle-left"></i> 通过油猴插件拦截并修改ajax请求
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/06/10/html-print/" rel="next" title="网页打印PDF文件">
                  网页打印PDF文件 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments gitalk-container"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="beian"><a href="https://beian.miit.gov.cn/" rel="noopener" target="_blank">冀ICP备17034993号-1 </a>
  </div>
  <div class="copyright">
    &copy; 2016 – 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">du qian</span>
  </div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>
  <div class="upyun-league">
    本网站由<a target="_blank" rel="noopener" href="https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral" style="border-bottom: none;">
      <img src="/images/upyun_logo.png" alt="又拍云" style="display: inline;height: 30px;vertical-align: bottom;"/>
    </a>提供CDN加速/云存储服务
  </div>


    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/duqian42707" class="github-corner" title="在 GitHub 上关注我" aria-label="在 GitHub 上关注我" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="/lib/animejs/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/sidebar.js"></script><script src="/js/next-boot.js"></script>

  <script src="/lib/hexo-generator-searchdb/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>


  <script class="next-config" data-name="mermaid" type="application/json">{"enable":true,"theme":"forest","js":{"url":"/lib/mermaid/dist/mermaid.min.js","integrity":"sha256-G8ouPAnw4zzMbnAenHnVz6h9XpKbNdOkrqTh7AadyHs="}}</script>
  <script src="/js/third-party/tags/mermaid.js"></script>





  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>




<link rel="stylesheet" href="/lib/gitalk/dist/gitalk.css" integrity="sha256-AJnUHL7dBv6PGaeyPQJcgQPDjt/Hn/PvYZde1iqfp8U=" crossorigin="anonymous">

<script class="next-config" data-name="gitalk" type="application/json">{"enable":true,"github_id":"duqian42707","repo":"blog-comment","client_id":"c9f48bc2fea3d4ce5d93","client_secret":"154d6227d3d7b532b36bfc1ce030121f0263ac90","admin_user":"duqian42707","distraction_free_mode":false,"proxy":"https://cors-anywhere.azm.workers.dev/https://github.com/login/oauth/access_token","language":"zh-CN","js":{"url":"/lib/gitalk/dist/gitalk.min.js","integrity":"sha256-MVK9MGD/XJaGyIghSVrONSnoXoGh3IFxLw0zfvzpxR4="},"path_md5":"573915efc1763260502a80e6e87478d8"}</script>
<script src="/js/third-party/comments/gitalk.js"></script>

</body>
</html>
